<?php

namespace App\Http\Controllers\Backend\System;

use App\Http\Controllers\BaseController;
use App\Http\Controllers\Controller;
use App\Interfaces\MenuInterface;
use App\Interfaces\RoleInterface;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class MenuController extends BaseController
{
    protected RoleInterface $role;

    protected MenuInterface $menu;

    public function __construct(RoleInterface $role, MenuInterface $menu)
    {
        $this->role = $role;
        $this->menu = $menu;
    }

    /**
     * 获取角色菜单
     * @param int $roleId
     * @return JsonResponse
     */
    public function getRoleMenu(int $roleId): JsonResponse
    {
        $role = $this->role->getRoleById($roleId);
        $menuIds = (array)json_decode($role->menuId);
        $menus = $this->menu->getAllMenu();
        foreach ($menus as $value)
        {
            $value->checked = in_array($value->menuId,$menuIds);
        }
        return $this->apiResult(['code'=>0,'message'=>'SUCCESS','data'=>$menus]);
    }

    /**
     * 查询所有菜单
     * @param Request $request
     * @return JsonResponse
     */
    public function getMenuAll(Request $request): JsonResponse
    {
        $params['title'] = $request->input('title');
        $params['path'] = $request->input('path');
        $params['authority'] = $request->input('authority');
        $menu = $this->menu->getMenuList($params);
        return $this->apiResult(['code'=>0,'data'=>$menu,'message'=>'SUCCESS']);
    }

    /**
     * 更新菜单
     * @param Request $request
     * @return JsonResponse
     */
    public function updateMenu(Request $request): JsonResponse
    {
        $data = $request->input();
        $data['updateTime'] = dateTime();
        $res = $this->menu->updateMenu($data);
        if (!$res)
        {
            return $this->apiResult(['code'=>1,'message'=>'修改菜单失败！']);
        }
        return $this->apiResult(['code'=>0,'message'=>'修改菜单'.$data['title'].'成功！']);
    }

    /**
     * 创建菜单
     * @param Request $request
     * @return JsonResponse
     */
    public function createMenu(Request $request): JsonResponse
    {
        $data = $request->input();
        $data['createTime'] = dateTime();
        $res = $this->menu->createMenu($data);
        if (!$res)
        {
            return $this->apiResult(['code'=>1,'message'=>'添加菜单失败！']);
        }
        return $this->apiResult(['code'=>0,'message'=>'添加菜单'.$data['title'].'成功！']);
    }

    /**
     * 删除菜单
     * @param int $menuId
     * @return JsonResponse
     */
    public function deleteMenu(int $menuId): JsonResponse
    {
        $data['deleted'] = 1;
        $data['updateTime'] = dateTime();
        $data['menuId'] = $menuId;
        $res = $this->menu->updateMenu($data);
        if (!$res)
        {
            return $this->apiResult(['code'=>1,'message'=>'删除菜单失败！']);
        }
        return $this->apiResult(['code'=>0,'message'=>'删除菜单'.$menuId.'成功！']);
    }
}
